import { ref, watch, nextTick } from 'vue';

/**
 * AI 功能相关逻辑
 */
export function useAiFeature(props, editorInstance, editorHasFocus) {
  // AI 状态
  const aiState = ref(!!props.aiEnabled);
  const showAiMarker = ref(false);
  const showAiPopover = ref(false);
  const aiTop = ref(0);
  const aiLeft = ref(32);
  const aiQuery = ref('');
  const popoverWidth = ref(480);
  const popoverOffsetLeft = ref(0);

  /**
   * 检查当前块是否为空行
   */
  const isCurrentBlockEmpty = () => {
    if (!editorInstance.value) return false;
    try {
      const editor = editorInstance.value;
      const selection = editor.selection;
      if (!selection) return false;
      const node = selection.getNode();
      if (!node) return false;
      
      const block = editor.dom.getParent(node, 'p,div,li,h1,h2,h3,h4,h5,h6') || node;
      const text = (block.textContent || '').trim();
      const onlyBr = block.children.length === 1 && block.children[0].tagName === 'BR';
      const isEmpty = text.length === 0 && (block.children.length === 0 || onlyBr);
      return isEmpty;
    } catch (_) {
      return false;
    }
  };

  /**
   * 清除所有 AI 相关属性
   */
  const clearAiAttributes = () => {
    if (!editorInstance.value) return;
    try {
      const body = editorInstance.value.getBody();
      body.querySelectorAll('[data-ai-hint]')?.forEach(el => el.removeAttribute('data-ai-hint'));
      body.querySelectorAll('[data-ai-empty]')?.forEach(el => el.removeAttribute('data-ai-empty'));
    } catch (err) {
      console.warn('清除 AI 属性时出错:', err);
    }
  };

  /**
   * 更新 AI 图标位置和显示状态
   */
  const updateAiMarker = (editorId) => {
    if (!aiState.value) {
      showAiMarker.value = false;
      clearAiAttributes();
      return;
    }
    if (!editorInstance.value || props.readonly) {
      showAiMarker.value = false;
      if (!showAiPopover.value) aiTop.value = 0;
      return;
    }
    // AI 只在编辑器有焦点时显示
    if (!editorHasFocus.value && !showAiPopover.value) {
      showAiMarker.value = false;
      clearAiAttributes();
      return;
    }
    
    const editor = editorInstance.value;
    const editable = document.getElementById(editorId);
    if (!editable) return;

    // 浮窗打开时，强制显示图标；否则检查是否为空行
    const shouldShowMarker = (showAiPopover.value || isCurrentBlockEmpty()) ? true : false;

    try {
      const selection = editor.selection;
      const rng = selection ? selection.getRng() : null;
      const node = selection?.getNode();
      if (!node) return;
      
      const block = editor.dom.getParent(node, 'p,div,li,h1,h2,h3,h4,h5,h6') || node;
      const blockRect = (block.getBoundingClientRect ? block.getBoundingClientRect() : editor.dom.getRect(block));
      const editableRect = editable.getBoundingClientRect();
      
      // 获取 .editable-wrapper（AI 组件的定位父元素）
      const wrapperEl = editable.closest('.editable-wrapper');
      const wrapperRect = wrapperEl ? wrapperEl.getBoundingClientRect() : editableRect;

      // 垂直定位：优先用光标 rect（相对 wrapper），否则用块 rect
      let top;
      if (rng && typeof rng.getClientRects === 'function') {
        const rects = rng.getClientRects();
        const caretRect = rects && rects.length > 0 ? rects[0] : null;
        if (caretRect) {
          top = caretRect.top - wrapperRect.top;
        }
      }
      if (top === undefined) {
        top = blockRect.top - wrapperRect.top;
      }
      
      const microTop = 2;
      aiTop.value = Math.max(0, top + microTop);
      
      // 边界检查：确保 AI 图标在可见区域内
      const wrapperHeight = wrapperEl ? wrapperEl.clientHeight : 0;
      const aiButtonHeight = 24;
      
      // 最终决定是否显示图标：需要满足基本条件且在可见区域内
      let finalShowMarker = shouldShowMarker;
      if (!showAiPopover.value) {
        if (top + aiButtonHeight > wrapperHeight || top < 0) {
          finalShowMarker = false;
        }
      }
      showAiMarker.value = finalShowMarker;

      // 水平定位：将图标放在光标左侧；退回到块左侧（相对 wrapper）
      const contentPaddingLeft = 32;
      const buttonWidth = 36;
      const gap = 8;
      const micro = 4;
      let left;
      if (rng && typeof rng.getClientRects === 'function') {
        const rects = rng.getClientRects();
        const caretRect = rects && rects.length > 0 ? rects[0] : null;
        if (caretRect) left = Math.max(contentPaddingLeft, caretRect.left - wrapperRect.left - (buttonWidth + gap + micro));
      }
      if (left === undefined) {
        left = Math.max(contentPaddingLeft, (blockRect.left - wrapperRect.left) - (buttonWidth + gap + micro));
      }
      aiLeft.value = left;

      // 控制空行提示：仅当当前为空行且显示行前图标，且浮窗未打开时显示
      const showHint = isCurrentBlockEmpty() && showAiMarker.value && !showAiPopover.value;
      // 先清除其他块上的提示标记
      try {
        const body = editor.getBody();
        body.querySelectorAll('[data-ai-hint]')?.forEach(el => el.removeAttribute('data-ai-hint'));
      } catch (_) {}
      if (showHint) {
        try { block.setAttribute('data-ai-hint', 'true'); } catch (_) {}
      }
    } catch (_) {}
  };

  /**
   * 计算可编辑区域尺寸
   */
  const computeEditableMetrics = (editorId) => {
    const editable = document.getElementById(editorId);
    if (!editable) return { contentWidth: 0, paddingLeft: 0, paddingRight: 0, rect: null };
    const rect = editable.getBoundingClientRect();
    const style = window.getComputedStyle(editable);
    const pl = parseFloat(style.paddingLeft || '0');
    const pr = parseFloat(style.paddingRight || '0');
    const contentWidth = rect.width - pl - pr;
    return { contentWidth, paddingLeft: pl, paddingRight: pr, rect };
  };

  /**
   * 获取光标位置
   */
  const getCaretRect = () => {
    if (!editorInstance.value) return null;
    const editor = editorInstance.value;
    const sel = editor.selection;
    const rng = sel ? sel.getRng() : null;
    if (!rng || typeof rng.getClientRects !== 'function') return null;
    const rects = rng.getClientRects();
    return rects && rects.length > 0 ? rects[0] : null;
  };

  /**
   * 更新浮窗布局
   */
  const updatePopoverLayout = (editorId) => {
    const metrics = computeEditableMetrics(editorId);
    const { contentWidth, paddingLeft, paddingRight, rect: editableRect } = metrics;
    const caretRect = getCaretRect();
    const editable = document.getElementById(editorId);
    const wrapperEl = editable ? editable.closest('.editable-wrapper') : null;
    const wrapperRect = wrapperEl ? wrapperEl.getBoundingClientRect() : (editableRect || { left: 0, width: 0 });
    
    if (contentWidth > 0) {
      if (caretRect && editableRect) {
        const contentLeftEdge = editableRect.left + paddingLeft;
        const contentRightEdge = editableRect.left + editableRect.width - paddingRight;
        const caretLeft = Math.max(contentLeftEdge, Math.min(caretRect.left, contentRightEdge));
        let width = Math.floor(contentRightEdge - caretLeft);
        if (!isFinite(width) || width <= 0) width = Math.floor(contentWidth);
        popoverWidth.value = Math.max(240, width);
        const caretLeftRelToWrapper = caretLeft - wrapperRect.left;
        popoverOffsetLeft.value = Math.max(0, Math.floor(caretLeftRelToWrapper - aiLeft.value));
      } else {
        popoverWidth.value = Math.max(240, Math.floor(contentWidth));
        const buttonWidth = 36;
        const gap = 8;
        popoverOffsetLeft.value = buttonWidth + gap;
      }
    }
  };

  /**
   * 打开 AI 浮窗
   */
  const openAiPopover = (editorId) => {
    showAiPopover.value = true;
    aiQuery.value = "";
    nextTick(() => updatePopoverLayout(editorId));
  };

  /**
   * 关闭 AI 浮窗
   */
  const closeAiPopover = (editorId) => {
    showAiPopover.value = false;
    nextTick(() => updateAiMarker(editorId));
  };

  /**
   * 提交 AI 查询
   */
  const submitAi = (editorId) => {
    closeAiPopover(editorId);
  };

  /**
   * 检查焦点是否在 AI 浮窗内
   */
  const isFocusInsideAiOverlay = (editorId) => {
    const aiRoot = document.getElementById(`${editorId}-ai-root`);
    return aiRoot && aiRoot.contains(document.activeElement);
  };

  /**
   * 光标移动时的布局更新
   */
  const relayoutOnCaretMove = (editorId) => {
    if (!showAiPopover.value) return;
    updatePopoverLayout(editorId);
  };

  return {
    // 状态
    aiState,
    showAiMarker,
    showAiPopover,
    aiTop,
    aiLeft,
    aiQuery,
    popoverWidth,
    popoverOffsetLeft,
    
    // 方法
    updateAiMarker,
    updatePopoverLayout,
    openAiPopover,
    closeAiPopover,
    submitAi,
    isFocusInsideAiOverlay,
    relayoutOnCaretMove,
    clearAiAttributes,
    isCurrentBlockEmpty,
  };
}
